var app = getApp();
var md5 = require('../../../libs/md5.js');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    showpicker: '',
    index:'',
    leixing: ['洗车行','加油站'],
    end: ['13:00', '14:00', '15:00', '16:00', '17:00', '18:00','19:00','20:00', '21:00', '22:00', '23:00', '24:00'],
    start: ['00:00', '01:00', '02:00', '03:00', '04:00','05:00', '06:00', '07:00', '08:00', '09:00', '10:00', '11:00', '12:00'],
    showtime:false,
    multiIndex:[],
    starttime:'',
    endtime:'',
    img1:'',
    img2:'',
    imgselected:0,
    imgselected2:0,
    latitude:0,
    longitude:0,
    address:'',
    xylist:'',
    id:'',
    shopdetail:{},
    shopid:'',
    checked:false,
    men:[],
    shopImg:[],  
    array: [{ value: 200, checked: false }, { value: 500, checked: false }, { value: 800, checked: false },{ value: 1000, checked: false }, { value: 2000, checked: false },{ value: '其它', checked: false }],
    store_index:'',
    store_money:'',
    showin:true,
    hidden:false,
    mden:false
    
  },
  //  数值
  arrbtn(e){
    let index = e.target.dataset.index;
    let array = this.data.array;
    array.map(item=>{
      item.checked = false
    })
    array[index].checked = true;
    if(index == 5){
      this.setData({
        store_money:0
      })
    }else{
      this.setData({
        store_money: array[index].value
      })
    }
    this.setData({
      array: array
    })
  },
  moneyInput: function(e){
    this.setData({
      store_money: e.detail.value
    });
  },
 
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
        
    
    if(options.id != undefined){
      this.setData({

        shopid:options.id,
      })
      this.getshop(options.id);
    }
  },
  /**
 * 生命周期函数--监听页面显示
 */
   
  onShow: function () {
    this.checkuser();
 
    that.setData({
      mden: false

    })
     
  },
  
  // 获取我的数据
  checkuser: function () {
    var that = this;
    setTimeout(function () {
      that.setData({
        mden: true

      })
      var status = wx.getStorageSync('status');
      var shop_id = wx.getStorageSync('shop_id');
      var shop_status = wx.getStorageSync('shop_status');
      console.log('status', status);
      if (parseInt(status) == 0) {
        wx.showModal({
          title: '温馨提示',
          content: '为确保是您本人操作请验证手机号',
          confirmText: '确定',
          showCancel: true,
          success: function (res) {
            if (res.confirm) {
              wx.navigateTo({
                url: '/pages/mine/mobile/mobile?type=40',
             })

            }

          }
        });
        
      }
      // if (parseInt(status) == 1) {
      //   wx.navigateTo({
      //     url: '/pages/mine/user-xx/user-xx',
      //   })
      // }
      if (shop_id) {
        if(shop_status == 1){
          wx.showModal({
            title: '提醒',
            content: '信息提交成功，请勿重复操作！',
            confirmText: '确定',
            showCancel: false,
            success: function (res) {
              if (res.confirm) {
                wx.switchTab({
                  url: '/pages/mine/user/user',
                })
                
              }

            }
          });
         
        } 
        if (shop_status == 2) {
          that.getshop(shop_id);
          wx.showModal({
            title: '提醒',
            content: '您的商家信息未通过审核，请重新提交',
            success: function (res) {
             return;
            }
          });
        }
        if (shop_status == 0) {
          wx.showModal({
            title: '提醒',           
            content: '您的信息处于审核状态',
            confirmText:'确定',
            showCancel:false,
            success: function (res) {
              if (res.confirm){
                wx.switchTab({
                  url: '/pages/mine/user/user',
                })
              }
             
            }
          });
        }
      }
    },2000);

  },
  bindPickerChange1(e){
    let arr = this.data.array
    this.setData({
      store_money: arr[e.detail.value].value
    })
  },
  // 获取商家默认信息
  getshop:function(id){
          var that = this;
          var param ={
            url:"api/shop/shopInfo",
            data:{
              shop_id: id
            },
            success:function(e){
              console.log(e)
              var imgselected;
              var imgselected2;
              // var url = $(this).data.men[0].url + $(this).data.men[1].url;  
        
              // e.data.data.mentou != '' ? imgselected = 1 : imgselected = 0;
              // e.data.data.yingye != '' ? imgselected2 = 1 : imgselected2 = 0;
              var type = e.data.data.type;
              if (parseInt(type) == 1 ){
                that.getinfo(2);
              }
              if (parseInt(type) == 2) {
                that.getinfo(1);
              }
              if (parseInt(type) == 3) {
                that.getinfo(3);
              }
              var index = parseInt(e.data.data.type) - 1;
              // var img1=$(this).data.men[0].id+$(this).men[1].id;
              // console.log(imag1)
              if (e.data.data.store_money != '0'){
                var array = that.data.array;
                var other = 0;
                var isother = true;
                array.map(item => {
                  other++;
                  
                  if (item.value == e.data.data.store_money){
                    isother = false;
                    item.checked = true;
                  }else{
                    if (other == 6 && isother){
                      item.checked = true;
                    }else{
                      item.checked = false;
                    }
                    
                  }
                  
                })
                that.setData({
                  store_money: e.data.data.store_money,
                  array:array
                });
              }
              that.setData({
                shopdetail:e.data.data,
                starttime:e.data.data.start_time,
                endtime:e.data.data.end_time,
                men: e.data.data.mentou.split(','),
                shopImg: e.data.data.yingye.split(','),
                imgselected:imgselected,
                imgselected2:imgselected2,
                address: e.data.data.address,
                index:index,
                shopid:e.data.data.id,
                latitude: e.data.data.latitude,
                longitude:e.data.data.longitude
              })
            }
          };
          app.post(param);
      
  },
  chooseimgs1: function(e){
    var that = this;
    var images = that.data.men;
    var timestamp = Date.parse(new Date()) / 1000;
    var random = Math.floor(Math.random() * 100);
    var sign = 'GHRDY65' + String(random) + String(timestamp);
    sign = md5.hexMD5(sign);
    wx.chooseImage({
      count: 9 - images.length,
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success: function (res) {
        // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
        for (var i = 0; i < res.tempFilePaths.length; i++) {
          wx.uploadFile({
            url: app.static.url + 'api/common/uploadFile',
            filePath: res.tempFilePaths[i],
            name: 'file',
            formData: {
              timestamp: timestamp,
              random: random,
              sign: sign
            },
            success: function (ret) {
              var data = ret.data;
              data = JSON.parse(data);
              if (data.code == 1) {
                that.setData({
                  men: that.data.men.concat(data.data.url),
                });
              }
            }
          })
        }
      }
    })
  },
  chooseimgs2: function (e) {
    var that = this;
    var images = that.data.shopImg;
    var timestamp = Date.parse(new Date()) / 1000;
    var random = Math.floor(Math.random() * 100);
    var sign = 'GHRDY65' + String(random) + String(timestamp);
    sign = md5.hexMD5(sign);
    wx.chooseImage({
      count: 9 - images.length,
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success: function (res) {
        // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
        for (var i = 0; i < res.tempFilePaths.length; i++) {
          wx.uploadFile({
            url: app.static.url + 'api/common/uploadFile',
            filePath: res.tempFilePaths[i],
            name: 'file',
            formData: {
              timestamp: timestamp,
              random: random,
              sign: sign
            },
            success: function (ret) {
              var data = ret.data;
              data = JSON.parse(data);
              if (data.code == 1) {
                that.setData({
                  shopImg: that.data.shopImg.concat(data.data.url),
                });
              }
            }
          })
        }
      }
    })
  },
  chooseimg: function (e) {
    let param = e.currentTarget.dataset;
    console.log(param)
    var that = this;
    var success = function (res) {
      var data = JSON.parse(res.data);
      var url = data.data.url;  
      let imgs;
      if (param.type == 1){
        imgs = that.data.men
        imgs.push(url)
        that.setData({
          men: imgs,
        })
      }else{
        imgs = that.data.shopImg
        imgs.push(url)
        that.setData({
          shopImg: imgs,
        })
      }
      
    }
    app.uploadimg(success);

  },
  
  delimg: function (e) {
    var that = this;
    let param = e.currentTarget.dataset;
    console.log(param)
    wx.showModal({
      title: '提醒',
      content: '确定要删除此图片吗？',
      success: function (res) {
        if (res.confirm) {
          let imgs = param.type ? that.data.men : that.data.shopImg;
          imgs.splice(param.index, 1)
          if(param.type){
            that.setData({
              men:imgs
            })
          }else{
            that.setData({
              shopImg: imgs
            })
          }
        } 
      }
    })
  },
  
  // 选择类型
  sleixing: function () {
    this.setData({
      showpicker: 1,
      index: 0
    })
    this.getinfo(2);
  },
  // 隐藏picker
  hidePicker: function () {
    this.setData({
      showpicker: 0
    })
  },
  // 
  bindPickerChange: function (e) {
    this.setData({
      index: e.detail.value
    })
    if (e.detail.value == 0){
      this.getinfo(2);
    }
    if (e.detail.value == 1) {
      this.getinfo(1);
    }
    if (e.detail.value == 2) {
      this.getinfo(3);
    }
  },

  // 选择时间
  stime: function () {
    this.setData({
      showtime: 1,
      starttime: this.data.start[0],
      endtime: this.data.end[0],
    })
   
  },
  hidetime:function(){
    this.setData({
      showtime: 0,
    })
  },
  timeChange: function (e) {
    var val = e.detail.value;
    this.setData({
      starttime: this.data.start[val[0]],
      endtime: this.data.end[val[1]],
    })
  },
  
  /**********用户地址选择**********/
  location: function () {
    this.getUserLocation();
  },

  /********用户授权********/
  getUserLocation: function () {
    let that = this
    wx.getSetting({
      success: (res) => {
        if (res.authSetting['scope.userLocation'] != undefined && res.authSetting['scope.userLocation'] != true) {
          // console.log('authSetting:status:拒绝授权后再次进入重新授权', res.authSetting['scope.userLocation'])
          wx.showModal({
            title: '',
            content: '我们需要获取你的地理位置，请确认授权',
            success: function (res) {
              if (res.cancel) {
                wx.showToast({
                  title: '拒绝授权',
                  icon: 'none'
                })
              } else if (res.confirm) {
                wx.openSetting({
                  success: function (dataAu) {
                    // console.log('dataAu:success', dataAu)
                    if (dataAu.authSetting["scope.userLocation"] == true) {
                      //再次授权，调用wx.getLocation的API
                      that.getLocation(dataAu)
                    } else {
                      wx.showToast({
                        title: '授权失败',
                        icon: 'none'
                      })
                    }
                  }
                })
              }
            }
          })
        }
        // 初始化进入，未授权
        else if (res.authSetting['scope.userLocation'] == undefined) {
          that.getLocation(res)
        }
        // 已授权
        else if (res.authSetting['scope.userLocation']) {
          that.getLocation(res)
        }
      }
    })
  },
  // 微信获得经纬度
  getLocation: function (userLocation) {
    let that = this
    wx.getLocation({
      type: "wgs84",
      isHighAccuracy:true,
      success: function (res) {
        // console.log('getLocation:success', res)
        var latitude = res.latitude
        var longitude = res.longitude
        that.moveToLocation();
      },
      fail: function (res) {
        // console.log('getLocation:fail', res)
        if (res.errMsg === 'getLocation:fail:auth denied') {
          wx.showToast({
            title: '拒绝授权',
            icon: 'none'
          })
          setTimeout(() => {
            wx.navigateBack()
          }, 1500)
          return
        }
        if (!userLocation || !userLocation.authSetting['scope.userLocation']) {
          that.getUserLocation()
        } else if (userLocation.authSetting['scope.userLocation']) {
          wx.showModal({
            title: '',
            content: '请在系统设置中打开定位服务',
            showCancel: false,
            success: result => {
              if (result.confirm) {
                wx.navigateBack()
              }
            }
          })
        } else {
          wx.showToast({
            title: '授权失败',
            icon: 'none'
          })
        }
      }
    })
  },
  // 
  //移动选点
  moveToLocation: function () {
    var that = this;
    wx.chooseLocation({
      success: function (res) {
        if (res.name != '') {
          that.setData({
            address: res.name,
            latitude:res.latitude,
            longitude:res.longitude,
          })
        }

      },
      fail: function (err) {
        console.log(err);
        wx.navigateBack({
          delta: 1
        });
      }
    });
  },

  submitform:function(e){
      console.log(e)
      var userid = wx.getStorageSync("userId");
      var img1 = this.data.img1;
      var img2 = this.data.img2;
      var checked = this.data.checked;
      var latitude = this.data.latitude;
      var longitude = this.data.longitude;
      var address = this.data.address;
      var leixing =0;
      var mendian = e.detail.value.mendian;
      var starttime = this.data.starttime;
      var endtime = this.data.endtime;
      var index = this.data.index;
      var that = this;
      var usually = 0;//普通
      var business = 0;//商务
      var offroad = 0;//越野
      var sale_usually = 0;//普通
      var sale_business = 0;//商务
      var sale_offroad = 0;//越野
      var price_1 = 0;//98
      var price_2 = 0;//92
      var price_3 = 0;//95
      var price_4 = 0;//0
      var sale_price_1 = 0;//98
      var sale_price_2 = 0;//92
      var sale_price_3 = 0;//95
      var sale_price_4 = 0;//0
      var oil_price = {};
      var car_price = {};
      var store_money = this.data.store_money;
      if (parseInt(this.data.index) == 0){
          leixing =1
      } else if (parseInt(this.data.index) == 1){
          leixing = 3
      }
      if (index == 0) {
        usually = e.detail.value.usually;//普通
        business = e.detail.value.business;//商务
        offroad = e.detail.value.offroad;//越野

        sale_usually = e.detail.value.sale_usually;//普通
        sale_business = e.detail.value.sale_business;//商务
        sale_offroad = e.detail.value.sale_offroad;//越野

        car_price.usually = usually;
        car_price.business = business;
        car_price.offroad = offroad;

        car_price.sale_usually = sale_usually;
        car_price.sale_business = sale_business;
        car_price.sale_offroad = sale_offroad;

      } else if (index == 1) {
        price_1 = e.detail.value.price_1;//98
        price_2 = e.detail.value.price_2;//92
        price_3 = e.detail.value.price_3;//95
        price_4 = e.detail.value.price_4;//0

        sale_price_1 = e.detail.value.sale_price_1;//98
        sale_price_2 = e.detail.value.sale_price_2;//92
        sale_price_3 = e.detail.value.sale_price_3;//95
        sale_price_4 = e.detail.value.sale_price_4;//0

        oil_price.price_1 = price_1;
        oil_price.price_2 = price_2;
        oil_price.price_3 = price_3;
        oil_price.price_4 = price_4;

        oil_price.sale_price_1 = sale_price_1;
        oil_price.sale_price_2 = sale_price_2;
        oil_price.sale_price_3 = sale_price_3;
        oil_price.sale_price_4 = sale_price_4;
      }
    console.log(that.data.men.length, that.data.shopImg.length, latitude, leixing, mendian)
      if(that.data.men.length == 0 || that.data.shopImg.length == 0||latitude ==''||leixing == '' || mendian == ''){
          wx.showToast({
            title: '请将数据补充完整',
            icon:'none',
            duration:3000
          })
          return false;
      } else if (index == 0 && (usually == '' || business == '' || offroad == '')){
            wx.showToast({
              title: '请将价格补充完整',
              icon: 'none',
              duration: 3000
            })
            return false;
      } else if (index == 1 && (price_2 == '' || price_3 == '' || price_4 == '') ){
            wx.showToast({
              title: '请将价格补充完整',
              icon: 'none',
              duration: 3000
            })
            return false;
         
      }else if (checked == false){
        wx.showToast({
          title: '同意用户协议才能使用哦',
          icon: 'none',
          duration: 2000
        })
        return false;
      }else{
        console.log(car_price)
        console.log(oil_price)
        oil_price = JSON.stringify(oil_price);
        car_price = JSON.stringify(car_price);
        console.log(car_price)
        console.log(oil_price)
        var datas={
          user_id: userid,
          type: leixing,
          mentou: that.data.men.join(','),
          yingye: that.data.shopImg.join(','),
          shop_name: mendian,
          start_time: starttime,
          end_time: endtime,
          address: address,
          longitude: longitude,
          latitude: latitude,
          store_money:store_money,
          car_price:car_price,
          oil_price:oil_price
        };
        if(that.data.shopid != ''){
          var shopid = that.data.shopid;
          console.log(shopid)
          datas.id = shopid;
          var param = {
            url: "api/shop/editShop",
            data: datas,
            success: function (e) {
              wx.showToast({
                title: e.data.msg,
                icon: "none",
                duration: 2000
              });
              if (e.data.code == 1) {
                setTimeout(function () {
                  wx.switchTab({
                    url: '/pages/mine/user/user',
                  })
                }, 2000)
              }
            },
            error: function (e) {
              wx.showToast({
                title: e.data.msg,
                icon: "none",
                duration: 2000
              });
            }
          };
          app.post(param);
        }else{
          var param = {
            url: "api/shop/shopEnter",
            data: datas,
            success: function (e) {
              console.log(e)
              wx.showToast({
                title: e.data.msg,
                icon: "none",
                duration: 2000
              });
              if (e.data.code == 1) {
                setTimeout(function () {
                  wx.switchTab({
                    url: '/pages/mine/user/user',
                  })
                }, 2000)
              }
            },
            error: function (e) {
              wx.showToast({
                title: e.data.msg,
                icon: "none",
                duration: 2000
              });
            }
          };
          app.post(param);
        }
          
      }
  },


  // 获取服务协议
  getinfo:function(inx){
    var that = this;
    var param = {
      url:"api/shop/getArticles",
      success:function(e){
        var data = e.data.data;
        console.log(data)
        that.setData({
          id:inx,
          xylist:e.data.data[inx]
        })
      }
    };
    app.post(param);
  },
  xuzhi:function(){
    this.setData({
      checked:!this.data.checked
    })
  }
})